package cn.xorange.commons.data.handler;

import cn.xorange.commons.data.annotation.MTable;
import cn.xorange.commons.data.configuration.GlobalDataConfig;
import cn.xorange.commons.data.constants.FieldConstants;
import cn.xorange.commons.data.core.entity.BaseEntity;
import cn.xorange.commons.utils.spring.SpringUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author : yangjian
 * date : 2024/1/13
 * description :
 */
@Component
public class DataFillHandler implements FillFieldHandle {

    IFillData fillData = SpringUtils.getBean("cn.xorange.commons.core.handler.FillDataImpl");
    @Override
    public <T extends BaseEntity> void fillInsert(T t) {
        MTable mTable = t.getClass().getAnnotation(MTable.class);
        if(Objects.nonNull(mTable) && mTable.logicDel()){
            GlobalDataConfig config = SpringUtils.getBean(GlobalDataConfig.class);
            setFieldValByName(FieldConstants.LOGIC_DEL, config.getLogicNotDeleteValue(), t);
        }
        setFieldValByName(FieldConstants.TENANT_ID, fillData.tenantId(), t);
        setFieldValByName(FieldConstants.CREATE_BY_ID, fillData.userId(), t);
        setFieldValByName(FieldConstants.CREATE_BY, fillData.userName(), t);
        setFieldValByName(FieldConstants.CREATE_TIME, new Date(), t);
    }

    @Override
    public <T extends BaseEntity> void fillUpdate(T t) {
        setFieldValByName(FieldConstants.UPDATE_BY_ID, fillData.userId(), t);
        setFieldValByName(FieldConstants.UPDATE_BY, fillData.userName(), t);
        setFieldValByName(FieldConstants.UPDATE_TIME, new Date(), t);
    }

}
